const Koa = require('koa');
const app = new Koa();
const router = require('./routes/routes')
const bodyParser = require('koa-bodyparser');
const { verifyToken } = require("./utils/index")
app.use(async (ctx, next) => {
    ctx.set('Access-Control-Allow-Origin', '*'); // 允许所有来源访问
    ctx.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); // 允许的请求方法
    ctx.set('Access-Control-Allow-Headers', 'Content-Type, Authorization'); // 允许的请求头
    try {
        let currentPath = ctx.path
        if (currentPath.includes(global.urlBase + '/login')) {
            return next()
        }
        let token = ctx.header.token;
        let decodedToken = verifyToken(token)
        if (decodedToken && decodedToken.username) {
            ctx.username = decodedToken.username;
            return next(); // 调用下一个中间件函数
        }
        ctx.body = {
            code: 401,
            msg: '未登录'
        }
    } catch (error) {
        ctx.body = {
            code: 401,
            msg: '未登录'
        }
    }

});

app.use(bodyParser());
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(8001, () => {
    console.log('启动成功');
});